package com.infore.airsupervise.ui.fragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.transition.Slide;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.EventAdapter;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.EventE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.EventBiz;
import com.infore.airsupervise.biz.impl.EventBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.activity.EventDetailsActivity;
import com.infore.airsupervise.ui.activity.EventEditorActivity;
import com.infore.airsupervise.ui.activity.EventsListActivity;
import com.infore.airsupervise.ui.activity.SearchDataRateActivity;
import com.infore.airsupervise.utils.DialogUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.yanzhenjie.loading.LoadingView;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017/8/17.
 */

public class AutoEventFragment extends BaseFragment
        implements SwipeRefreshLayout.OnRefreshListener, EventsListActivity.OnDataTypeChangeListener {

    @BindView(R.id.refreshRecyclerView)
    SwipeMenuRecyclerView mRecyclerView;

    @BindView(R.id.event_auto_Refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.create_event)
    FloatingActionButton createEvent;

    private EventAdapter mAdapter;

    private List<EventE> bean = new ArrayList<>();

    private EventBiz eventBiz;

    private static int refreshpage = 1;
    private boolean loaddata = false;
    private SweetAlertDialog dialog;

    private boolean firstLoadData = false;

    private int recordtype=0;

    private EventsListActivity parentContent;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_autoevent, container, false);
        ButterKnife.bind(this, view);
        parentContent = (EventsListActivity) getActivity();
        eventBiz = new EventBizImpl();
        initView();
        return view;
    }


    /**
     * 初始化控件
     */
    private void initView() {

        mRefresh.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mRecyclerView.setSwipeItemClickListener(mItemClickListener); // RecyclerView Item点击监听。
        // 自定义的核心就是DefineLoadMoreView类。
        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(getActivity());
        mRecyclerView.addFooterView(loadMoreView); // 添加为Footer。
        mRecyclerView.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
        mRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。
        mAdapter = new EventAdapter(getActivity(), bean, 1);
        mRecyclerView.setAdapter(mAdapter);

        onRefresh();
    }


    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_50);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem addItem = new SwipeMenuItem(getActivity())
                    .setBackground(R.drawable.selector_green)
                    .setText("编辑")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);

            SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                    .setBackground(R.drawable.selector_red)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);




            switch (viewType) {
                case 1:
                    swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
                    swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

                    break;
                case 2:
                    //  swipeRightMenu.addMenuItem(null);
                    //当不可编辑的时候 什么都不需要做就可以了
                    break;
            }
        }
    };


    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
            EventE eventE = bean.get(adapterPosition);
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                if(menuPosition==0){

                    if (eventE != null) {
                        Intent intent = new Intent(getActivity(), EventEditorActivity.class);
                        intent.putExtra("eventid", eventE.getId());
                        intent.putExtra("editor", 1);
                        startActivityForResult(intent,request);
                    }
                }else{


                    dialog = new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE);
                    dialog .setTitleText("确定删除？")
                            .setContentText("删除后将不能恢复")
                            .setConfirmText("继续删除")
                            .setCancelText("不删了")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    dialog.dismiss();
                                }
                            })
                            .show();

                }

              //  Toast.makeText(getActivity(), "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();

            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {


            }
        }
    };

    /**
     * Item点击监听。
     */
    private SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            EventE eventE = bean.get(position);
            if (eventE != null) {
                // JumpUtil.jumpFromTo(getActivity(), EventDetailsActivity.class, "eventid", eventE.getId());
                Intent intent = new Intent(getActivity(), EventDetailsActivity.class);
                intent.putExtra("eventid", eventE.getId());
                intent.putExtra("flag", eventE.getFlag());
                startActivityForResult(intent,request);
            }
        }
    };

    @Override
    public void onRefresh() {
        loaddata = false;
        loadData();
    }


    /**
     * 上拉加载更多
     */

    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            loaddata = true;
            //loading dialog
            loadData();
        }
    };


    private void loadData() {

        if (!firstLoadData) {
            dialog = new SweetAlertDialog(getContext(), SweetAlertDialog.PROGRESS_TYPE)
                    .setTitleText(MsgConst.HARD_LOADING)
                    .setContentText(MsgConst.PLEASE_WAITING);
            dialog.setCancelable(false);
            dialog.show();
        }

        if (!loaddata) {
            refreshpage = 0;
            firstLoadData = true;
        }

        eventBiz.getEventList("0", refreshpage,recordtype, new OnServerResponseListener<List<EventE>>() {
            @Override
            public void onSucceed(List<EventE> result, String desc) {
                if (loaddata) {
                    bean.addAll(result);
                    mAdapter.notifyItemRangeInserted(bean.size() - result.size(), result.size());
                    if (result.size() == 0) {
                        mRecyclerView.loadMoreFinish(false, false);
                    }

                } else {
                    bean.clear();
                    bean.addAll(result);
                    mAdapter.notifyDataSetChanged();
                    mRefresh.setRefreshing(false);
                    mRecyclerView.loadMoreFinish(false, true);
                }

                if (result.size() != 0) {
                    mRecyclerView.loadMoreFinish(false, true);
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (loaddata) {
                    refreshpage++;
                }
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //dialog 错误 异常提示
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @OnClick(R.id.create_event)
    public void onViewCreateEvent(View v) {

//        JumpUtil.jumpFromTo(getActivity(), EventEditorActivity.class, "editor", 2);
        Intent it  = new Intent(getActivity(), EventEditorActivity.class);
        it.putExtra("editor", 2);
        startActivityForResult(it,500);
    }

    @Override
    public void onDataTypeChange(int dataType) {
        mRefresh.setRefreshing(true);
            this.recordtype = dataType;
            onRefresh();

    }



    /**
     * 这是这个类的主角，如何自定义LoadMoreView。
     */
    static final class DefineLoadMoreView extends LinearLayout implements SwipeMenuRecyclerView.LoadMoreView, View.OnClickListener {

        private LoadingView mLoadingView;
        private TextView mTvMessage;

        private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener;

        public DefineLoadMoreView(Context context) {
            super(context);
            setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
            setGravity(Gravity.CENTER);
            setVisibility(GONE);

            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

            int minHeight = (int) (displayMetrics.density * 10 + 0.5);
            setMinimumHeight(minHeight);

            inflate(context, R.layout.layout_fotter_loadmore, this);
            mLoadingView = (LoadingView) findViewById(R.id.loading_view);
            mTvMessage = (TextView) findViewById(R.id.tv_message);

            int color1 = ContextCompat.getColor(getContext(), R.color.google_red);
//            int color2 = ContextCompat.getColor(getContext(), R.color.google_red);
//            int color3 = ContextCompat.getColor(getContext(), R.color.google_red);

            mLoadingView.setCircleColors(color1, color1, color1);
            setOnClickListener(this);
        }

        /**
         * 马上开始回调加载更多了，这里应该显示进度条。
         */
        @Override
        public void onLoading() {
            setVisibility(VISIBLE);
            mLoadingView.setVisibility(VISIBLE);
            mTvMessage.setVisibility(VISIBLE);
            mTvMessage.setText("正在努力加载，请稍后");
        }

        /**
         * 加载更多完成了。
         *
         * @param dataEmpty 是否请求到空数据。
         * @param hasMore   是否还有更多数据等待请求。
         */
        @Override
        public void onLoadFinish(boolean dataEmpty, boolean hasMore) {
            if (!hasMore) {
                setVisibility(VISIBLE);

                if (dataEmpty) {
                    mLoadingView.setVisibility(GONE);
                    mTvMessage.setVisibility(VISIBLE);
                    mTvMessage.setText("暂时没有数据");
                } else {
                    mLoadingView.setVisibility(GONE);
                    mTvMessage.setVisibility(VISIBLE);
                    mTvMessage.setText("没有更多数据啦");
                }
            } else {
                setVisibility(INVISIBLE);
            }
        }

        /**
         * 调用了setAutoLoadMore(false)后，在需要加载更多的时候，这个方法会被调用，并传入加载更多的listener。
         */
        @Override
        public void onWaitToLoadMore(SwipeMenuRecyclerView.LoadMoreListener loadMoreListener) {
            this.mLoadMoreListener = loadMoreListener;

            setVisibility(VISIBLE);
            mLoadingView.setVisibility(GONE);
            mTvMessage.setVisibility(VISIBLE);
            mTvMessage.setText("点我加载更多");
        }

        /**
         * 加载出错啦，下面的错误码和错误信息二选一。
         *
         * @param errorCode    错误码。
         * @param errorMessage 错误信息。
         */
        @Override
        public void onLoadError(int errorCode, String errorMessage) {
            setVisibility(VISIBLE);
            mLoadingView.setVisibility(GONE);
            mTvMessage.setVisibility(VISIBLE);

            // 这里要不直接设置错误信息，要不根据errorCode动态设置错误数据。
            mTvMessage.setText(errorMessage);
        }

        /**
         * 非自动加载更多时mLoadMoreListener才不为空。
         */
        @Override
        public void onClick(View v) {
            if (mLoadMoreListener != null) mLoadMoreListener.onLoadMore();
        }
    }

    private final  int request = 400;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            if(requestCode == request ){   //从编辑 和 处理返回时
                mRefresh.setRefreshing(true);
                onRefresh();
            }else if(requestCode == 500){   //从创建返回时
                parentContent.setCreateFromAuto(true);
            }
        }
    }
}
